import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
import ElementUI from 'element-ui';

import Login from 'components/user/login.vue';
import ScanRecord from 'components/user/scan_record.vue';
import Personal from 'components/user/personal.vue';

let login_to_route_name = '';
let router = new Router({
	routes: [
		{ path: '(/login)?', name: 'login', component: Login },
		{ path: '/scan_record', name: 'scan_record', component: ScanRecord },
		{ path: '/personal', name: 'personal', component: Personal },
	]
})
let checkLogin = (callback, show_error = true) => {
	Vue.prototype.$axios.get('/user/isLogin').then(res => {
		if(res.s != 1 && show_error) {
			ElementUI.Message.error(res.m || '未知异常');
		}
		callback(res.s);
	}, () => {
		callback('net_error');
	});
}
let login_name = 'login';
router.beforeEach((to, from, next) => {
	let to_type = to.params.type;

	if(to_type == 'no_check') {
		next();
	}else {
		if(from.name && to.name == login_name || (to_type && to_type == 'check_login')) {
		//logout or check_login fail
			login_to_route_name = from.name;
			next();
		}else {
			checkLogin(res => {
				if(res == 1) {
					if(to.name == login_name || (to.name=='scan_record' && to_type && to_type == 'login')) {
						//refresh login or input to login or login
						if(!login_to_route_name || login_to_route_name == login_name){
							login_to_route_name = 'scan_record';
						}
						let t_login_to_route_name = login_to_route_name;
						login_to_route_name = '';
						if(t_login_to_route_name == to.name) {
							next();
						}else {
							next({name:t_login_to_route_name, params:{type:'no_check'}});
						}
					}else {
						next();
					}
				}else if(res == 'Lg000') {
					if(to.name == login_name) {
						next();
					}else {
						login_to_route_name = to.name;
						next({name:login_name, params:{type:'check_login'}});
					}
				}
			}, to.name != login_name);
		}
	}
});
export default router;